<?php
namespace app\admin\controller;

use app\admin\model\Node;
use app\admin\model\NodeModel;
use app\admin\model\RoleModel;
use app\admin\model\DepartmentModel;
use think\Db;

class Role extends Base
{
	/**
	 * [角色列表]
	 */
    public function index(){
        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if ($param['searchText'] != '') {
                $where['role_name'] = ['like', '%' . $param['searchText'] . '%'];
            }
            $user = new RoleModel();
            $data['rows'] = $user->getRoleByWhere($where, $offset, $limit);
			$data['total'] = $user->getAllRole($where);
			return ['code'=>1,'msg'=>'加载成功','data'=>$data];
        }
        return $this->fetch();
    }

    // 添加角色
    public function roleAdd(){
        if(request()->isPost()){
            $param = input('post.');
            $role = new RoleModel();
            $flag = $role->insertRole($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        return $this->fetch();
    }

    // 编辑角色
    public function roleEdit(){
        $role = new RoleModel();
        if(request()->isPost()){
            $param = input('post.');
            $flag = $role->editRole($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $id = input('param.id');
        $this->assign([
            'role' => $role->getOneRole($id)
        ]);
        return $this->fetch();
    }

    // 删除角色
    public function roleDel()
    {
        $id = input('param.id');
        $role = new RoleModel();
        $flag = $role->delRole($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

	public function isHaveSon($node_id) {
		$count = DB::name("node")->where('type_id',$node_id)->count();
		if($count == 0){
			return false;
		}else{
			return true;
		}
	}

    /**
     * [分配操作权限]
     */
    public function giveAccess()
    {
        $param = input('param.');
        $node = new NodeModel();
        // 获取现在的权限
        if('get' == $param['type']){
            $arr = $node->getNodeInfo($param['id']);
			$arr['node'] = arr2tree($arr['node'],'id','pid','children');
			if(!empty($arr['rule'])){
				foreach($arr['rule'] as $k => $v){
					if($this->isHaveSon($v)){
						unset($arr['rule'][$k]);
					}
				}
			}
            return ['code'=>1,'msg'=>'加载成功','data'=>$arr];
        }
        // 分配新权限
        if('give' == $param['type']){
			if(!isset($param['rule'])){
				$param['rule'][] = 0;
			}
            $doparam = [
                'id' => $param['id'],
                'rule' => implode(",",$param['rule'])
            ];
            $user = new RoleModel();
            $flag = $user->editAccess($doparam);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
    }
}
